package com.qfedu.edu.interceptor;

import com.qfedu.edu.exception.handler.BusinessException;
import com.qfedu.edu.result.R;
import com.qfedu.edu.result.ResponseCode;
import com.qfedu.edu.slot.base.SlotChain;
import com.qfedu.edu.utils.HttpResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author xiaobobo
 * @title: GlobleInterceptor
 * @projectName cd-fy-2401-third-project-parent
 * @description: TODO
 * @date 2024/9/23  15:23
 */
@Component
@Slf4j
public class GlobalInterceptor implements HandlerInterceptor {

    @Autowired
    private SlotChain slotChain;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("执行到了全局的拦截器中....");
        try {
            slotChain.dealReq(request);
            log.info("slot执行通过...");
            return true;
        } catch (Exception e) {
            //说明执行SLOT执行了问题
            //通知前端执行Slot执行问题
            if(e instanceof BusinessException){
                //说明抛出的是可预期的异常
                BusinessException businessException= (BusinessException) e;
                R error = R.error(businessException.getCode(), businessException.getMsg());
                //然后通知前端
                HttpResponseUtils.sendResponse(response,error);
            }else{
                //说明抛出的是未知的异常....
                R error = R.error(ResponseCode.SLOT_INVOKE_EXCEPTION);
                HttpResponseUtils.sendResponse(response,error);
            }
        }
        log.info("slot执行未通过....");
        return false;
    }
}
